package com.atguigu.gulimall.product.controller;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.UUID;

@Controller
public class TestController {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedissonClient redissonClient;

    //读写锁测试

    /**
     * 读 + 读 无锁
     * 写 + 读 等待写锁释放
     * 写 + 写 阻塞
     * 读 + 写 等待读锁释放
     * @return
     */

    @GetMapping("/write")
    @ResponseBody
    public String writeLock(){
        RLock rLock = redissonClient.getReadWriteLock("wr-lock").writeLock();
        String s = "";
        try {
            rLock.lock();
            System.out.println("写锁加锁成功："+ Thread.currentThread().getId());
            s = UUID.randomUUID().toString();
            Thread.sleep(30000);
            redisTemplate.opsForValue().set("writeValue", s);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
            System.out.println("写锁解锁成功："+ Thread.currentThread().getId());
        }

        return s;
    }

    @GetMapping("/read")
    @ResponseBody
    public String readLock() {
        RLock rLock = redissonClient.getReadWriteLock("wr-lock").readLock();
        String s = "";
        try {
            rLock.lock();
            System.out.println("读锁加锁成功："+ Thread.currentThread().getId());
            s = redisTemplate.opsForValue().get("writeValue");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
            System.out.println("读锁解锁成功："+ Thread.currentThread().getId());
        }

        return s;
    }
}
